using System.Linq;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class UiSkillTreeSlot : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, ISavable
{
    private Ui ui;
    [SerializeField] private string skillName;
    [TextArea][SerializeField] private string skillDescription;
    [SerializeField] private Color lockedSkillColor;
    public bool unlocked;

    [SerializeField] private UiSkillTreeSlot[] shouldBeUnlocked;
    [SerializeField] private UiSkillTreeSlot[] shouldBeLocked;
    private Image skillImage;
    [SerializeField] private int skillPrice;

    private void OnValidate()
    {
        gameObject.name = $"SkillTreeSlotUi - {skillName}";
    }

    private void Awake()
    {
        skillImage = GetComponent<Image>();
        skillImage.color = lockedSkillColor;
        GetComponent<Button>().onClick.AddListener(Unlock);
        ui = FindAnyObjectByType<Ui>();
    }

    private void Start()
    {
        skillImage.color = unlocked ? Color.white : lockedSkillColor;
    }

    private void Unlock()
    {
        if (!PlayerManager.Instance.HaveEnoughMoney(skillPrice)) return;
        if (shouldBeUnlocked.Any(t => t.unlocked == false) || shouldBeLocked.Any(t => t.unlocked)) return;
        unlocked = true;
        skillImage.color = Color.white;
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        ui.SkillTooltip.Show(skillDescription, skillName, skillPrice);
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        ui.SkillTooltip.Hide();
    }

    public void Load(GameData data)
    {
        if (data.skillTree.TryGetValue(skillName, out bool isUnlocked))
        {
            unlocked = isUnlocked;
        }
    }

    public void Save(ref GameData data)
    {
        if (data.skillTree.TryGetValue(skillName, out bool isUnlocked))
        {
            _ = data.skillTree.Remove(skillName);
            data.skillTree.Add(skillName, unlocked);
        }
        else
        {
            data.skillTree.Add(skillName, unlocked);
        }
    }
}